﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.Common;
using System.Collections;
using System.Collections.ObjectModel;
using Portal.Workflow.Model;
using Portal.Workflow.Utilities;
using Portal.Workflow.Library;
using Portal.Web.Model;
using Portal.Core;
using Portal.Web.Utility;
using Portal.Utility;

namespace Portal.Workflow.Bussiness
{
    public class AjaxWorkflowTaskNextLink
    {
        string SessionId = System.Guid.NewGuid().ToString();
        
        public void RegiterAjaxPro()
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxWorkflowTaskNextLink));
        }


        public static string GetAjaxProNextLinkJavascript(string SiteId,string ContentWorkflow,string DivMainForm)
        {
            string JavascriptText =
                "<script language=\"javascript\">\r\n" +
              

                "   function ClientWorkflowProcessRoleCheckChange(RoleId)\r\n"+
                "   {\r\n"+
                "       RoleCheckedIds=document.getElementById('txtWfCheckRoleIds').value;\r\n"+
                "       Checked=document.getElementById('chkWfRole'+RoleId).checked;\r\n" +
                "       RetValue = Portal.Workflow.Bussiness.AjaxWorkflowTaskNextLink.ServerSideProcessRoleCheckChange(SiteId,RoleCheckedIds,RoleId,Checked).value;\r\n" +
                "       document.getElementById('txtWfCheckRoleIds').value=RetValue;\r\n" +
                "   }\r\n"+

                "   function ClientCancelDoNextLink()\r\n"+
                "   {\r\n"+
                "       document.getElementById('"+ContentWorkflow+"').style.display=\"none\";\r\n"+
                "       document.getElementById('"+DivMainForm+"').style.display=\"\";\r\n"+
                "   }\r\n"+

                "    function ClientDoNextLink(LinkId){\r\n" +
                "        SiteId='" + SiteId + "';\r\n" +
                "        WorkflowActionId=document.getElementById(\"txtWorkflowActionId\").value;\r\n" +
                "        WorkflowDefId=document.getElementById(\"txtWorkflowDefId\").value;\r\n" +
                "        RecordId=document.getElementById(\"txtRecordId\").value;\r\n" +
                //"        ExtraInfo=document.getElementById(\"txtExtraInfo\").value;\r\n" +
                "        oReturnParam=Portal.Workflow.Bussiness.AjaxWorkflowTaskNextLink.ServerSideGetLinkUrl(SiteId, WorkflowDefId,WorkflowActionId, RecordId,  LinkId).value;\r\n" +
                "        if(oReturnParam.IsError)\r\n"+
                "        {\r\n"+
                "           alert(oReturnParam.HtmlContent);\r\n"+
                "           return;\r\n"+
                "        }\r\n"+
                "        if(oReturnParam.IsLink)\r\n" +
                "        {\r\n" +
                "           window.open(oReturnParam.Url,'_self');\r\n"+
                "           return;\r\n"+
                "        }\r\n" +
                "        else\r\n"+
                "        {\r\n"+
                "           WfRoleIds=document.getElementById(\"txtWfCheckRoleIds\").value;\r\n" +
                "           ProcessContent=document.getElementById(\"txtProcessContent\").value;\r\n" +
                "           oDoNextLinkRetCls=Portal.Workflow.Bussiness.AjaxWorkflowTaskNextLink.ServerSideDoNextLink(SiteId, WorkflowDefId, WorkflowActionId, RecordId, LinkId, ProcessContent, WfRoleIds).value;\r\n" +
                "           if(oDoNextLinkRetCls.IsError==true)\r\n" +
                "           {\r\n" +
                "               alert(oDoNextLinkRetCls.ReturnMsg);\r\n" +
                "               return;\r\n" +
                "           }\r\n" +
                "           if(oDoNextLinkRetCls.IsLink)\r\n"+
                "           {\r\n"+
                "               window.open(oDoNextLinkRetCls.Url,'_self');\r\n"+
                "               return;\r\n"+
                "           }\r\n"+
                "           alert(oDoNextLinkRetCls.ReturnMsg);\r\n" +
                "           window.open(oDoNextLinkRetCls.Url,'_self');\r\n"+
                "       }\r\n"+
                "   };\r\n" +
                "</script>\r\n";
            return JavascriptText;
        }

        [AjaxPro.AjaxMethod]
        public string Draw(string SiteId, string WorkflowDefId, string WorkflowActionId, string RecordId, string LinkId)
        {
            SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);

            string RetHtml =
                "<input id=\"txtAttachFileSessionId\" type=\"hidden\" value=\"" + SessionId + "\">\r\n" +
                "<div id=\"divAjaxWorkflowTaskNextLink\" class=\"CssWorkflowTaskContentNextLink\">" + GetNextLinkForm(SiteId, WorkflowDefId, WorkflowActionId, RecordId, LinkId) + "</div>\r\n";
            return RetHtml;
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideProcessRoleCheckChange(string SiteId, string RoleCheckedIds, string RoleId, bool Checked)
        {
            if (Checked)
            {
                if (!string.IsNullOrEmpty(RoleCheckedIds))
                {
                    RoleCheckedIds = RoleCheckedIds + ";";
                }
                RoleCheckedIds = RoleCheckedIds + "$"+RoleId+"$";
            }
            else
            {
                RoleCheckedIds = RoleCheckedIds.Replace("$"+RoleId+"$", "");
            }
            RoleCheckedIds = RoleCheckedIds.Replace(";;", ";");
            RoleCheckedIds = RoleCheckedIds.Trim();
            if (RoleCheckedIds.Length > 0)
            {
                if (RoleCheckedIds[0].ToString().Equals(";"))
                {
                    RoleCheckedIds = RoleCheckedIds.Substring(1);
                }
            }
            return RoleCheckedIds;
        }

        RetNextLinkParam GetLinkUrl(
            Workflow.Library.WorkFlowApp wfa, 
            string SiteId, 
            string LinkId,
            string RecordId,
            string WorkflowDefId,
            string WorkflowActionId)
        {
            SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            RetNextLinkParam ORetNextLinkParam = null;
            LinkCls oLinkCls = wfa.GetLink(LinkId);
            if (String.IsNullOrEmpty(oLinkCls.RunFunctionId) == false)
            {
                string[] FunctionIds = oLinkCls.RunFunctionId.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                for (int iIndex = 0; iIndex < FunctionIds.Length; iIndex++)
                {
                    string DllPath = oSiteParam.DllPath;
                    IWfFunction
                        WfFunction = WorkFlowFunctionMan.Find(DllPath, FunctionIds[iIndex]);
                    if (WfFunction != null)
                    {
                        WfExecuteParamCls oWfExecuteParamCls = new WfExecuteParamCls();
                        oWfExecuteParamCls.RecordId = RecordId;
                        oWfExecuteParamCls.WorkflowDefId = WorkflowDefId;
                        oWfExecuteParamCls.WorkflowActionId = WorkflowActionId;
                        oWfExecuteParamCls.SiteId = SiteId;
                        //oWfExecuteParamCls.ExtraParam = ExtraInfo;

                        ORetNextLinkParam = WfFunction.GetLinkUrl(oWfExecuteParamCls);
                    }
                }
            }
            return ORetNextLinkParam;
        }

        [AjaxPro.AjaxMethod]
        public ReturnParamCls ServerSideGetLinkUrl(
            string SiteId,
            string WorkflowDefId,
            string WorkflowActionId,
            string RecordId,
            string LinkId)
        {
            ReturnParamCls oReturnParamCls = new ReturnParamCls();
            try
            {
                //string Html = "";
                SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                Workflow.Library.WorkFlowApp wfa = WorkflowBll.CreateWorkflowAppFromWorkflowAction(oSiteParam.ConnectionString, WorkflowActionId);

                RetNextLinkParam ORetNextLinkParam = GetLinkUrl(wfa, SiteId, LinkId, RecordId, WorkflowDefId, WorkflowActionId);
                if (ORetNextLinkParam!=null)
                {
                    oReturnParamCls.IsLink = true;
                    oReturnParamCls.Url = ORetNextLinkParam.Url;
                    ///Update by dvtien
                    //fix to rewrite url
                    if (oReturnParamCls.Url.IndexOf("Update") != -1) {
                        oReturnParamCls.Url = GetUrlUpdate("update", RecordId, oSiteParam);
                    }
                    ///end
                    oReturnParamCls.Target = ORetNextLinkParam.Target;
                    oReturnParamCls.HtmlContent = "Thực hiện mở liên kết! Xin vui lòng chọn nút [thực hiện xử lý] để thực hiện đường chuyển";
                    
                }
            }
            catch (Exception ex)
            {
                oReturnParamCls.IsError = true;
                oReturnParamCls.HtmlContent = ex.Message.ToString();
            }
            return oReturnParamCls;
        }

        public static string GetUrlUpdate(string Subject, string CmsDataId, SiteParam OSiteParam)
        {           
            string HttpDataRoot = WebConfig.GetConfigFromXml(OSiteParam, "HttpAdminRoot");
            string Url = HttpDataRoot + "/" + Subject + "-ud-" + CmsDataId + "." + "aspx";
            return Url;
        }


        [AjaxPro.AjaxMethod]
        public DoNextLinkRetCls ServerSideDoNextLink(
            string SiteId,
            string WorkflowDefId,
            string WorkflowActionId,
            string RecordId,
            string LinkId,
            string ProcessContent,
            string CheckedRoleIds)
        {
            DoNextLinkRetCls oDoNextLinkRetCls = new DoNextLinkRetCls();
            SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            Workflow.Library.WorkFlowApp wfa = WorkflowBll.CreateWorkflowAppFromWorkflowAction(oSiteParam.ConnectionString, WorkflowActionId);
            int HasResponsible = 0;
            string ResponsibleId = "";
            string AttachedDocumentIds = "";
            //string ProcessDate = "";
            string AttachFileSessionId = "";
            string Joiner = "";
            string JoinerId = "";
            string Responsible = "";
            //if (string.IsNullOrEmpty(AttachedDocumentIds)) AttachedDocumentIds = "";
            CheckedRoleIds = CheckedRoleIds.Replace("$", "");
            try
            {
                RetNextLinkParam ORetNextLinkParam = GetLinkUrl(wfa, SiteId, LinkId, RecordId, WorkflowDefId, WorkflowActionId);
                if (ORetNextLinkParam!=null)
                {
                    oDoNextLinkRetCls.IsLink = true;
                    oDoNextLinkRetCls.Url = ORetNextLinkParam.Url;
                    oDoNextLinkRetCls.Target = ORetNextLinkParam.Target;
                    return oDoNextLinkRetCls;
                }

                //chuyen thanh login
                if (HasResponsible == 1)
                {
                    if (string.IsNullOrEmpty(ResponsibleId)) throw new Exception("Vui lòng chọn chủ trì!");
                }
                int iProcessDate = 2;

                //if (!string.IsNullOrEmpty(ProcessDate))
                //{
                //    try
                //    {
                //        DateTime dDateProcess = FunctionUtilities.VNDateToDate(ProcessDate);
                //        iProcessDate = dDateProcess.Subtract(System.DateTime.Now).Days;
                //    }
                //    catch
                //    {
                //        throw new Exception("Hạn xử lý nhập không hợp lệ!");
                //    }
                //}
                string WorkflowFunction = "";

                //string SendToUserIds = wfa.ConvertFullIds(FullNameSendToUserIds);
                //string CCToUserIds = wfa.ConvertFullIds(FullNameCCToUserIds);
                
                string[] RoleIds = CheckedRoleIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                LinkCls oLinkCls = new WorkflowBll().GetLink(wfa, LinkId);
                
                Collection<Portal.Systems.Model.UserCls> ColUsers = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingUserBelongRoleForWorkflow(SiteId, RoleIds);
                string BatchId = System.Guid.NewGuid().ToString();
                
                Collection<EmployeeCls> ColSentToEmployees = new Collection<EmployeeCls> { };
                for (int iIndexUser = 0; iIndexUser < ColUsers.Count; iIndexUser++)
                {
                    //doan nay lay tai khoan...!
                    EmployeeCls OEmployee = new EmployeeCls();
                    OEmployee.EmployeeId = ColUsers[iIndexUser].UserId;
                    OEmployee.BatchId = BatchId;
                    OEmployee.FullName = ColUsers[iIndexUser].FullName;
                    OEmployee.LoginName = ColUsers[iIndexUser].LoginName;
                    OEmployee.OfficeCode = ColUsers[iIndexUser].AssetCode;
                    OEmployee.ProcessType = "to";
                    OEmployee.TempRoleId = new string[] { ColUsers[iIndexUser].RoleId };
                    
                    RoleCls OWorkflowRole = new RoleCls();
                    OWorkflowRole.RoleId = ColUsers[iIndexUser].RoleModel.RoleId;
                    OWorkflowRole.RoleName = ColUsers[iIndexUser].RoleModel.RoleName;
                    OEmployee.ToRole = OWorkflowRole;
                    ColSentToEmployees.Add(OEmployee);
                }

                if (oLinkCls.NextForStatus == 0 && oLinkCls.ForAllEmployeeInRole == 1 && oLinkCls.FinishThisTask == 0)
                {
                    if (ColSentToEmployees.Count == 0)
                    {
                        throw new Exception("Đường xử lý công việc này cần xác định đối tượng xử lý!");
                    }
                }
                EmployeeCls[] DedicateUsers = new EmployeeCls[ColSentToEmployees.Count];
                ColSentToEmployees.CopyTo(DedicateUsers,0);

                DataSet dsUsers = new DataSet();
                dsUsers.Tables.Add("Info");
                dsUsers.Tables["Info"].Columns.Add("EmployeeId");
                dsUsers.Tables["Info"].Columns.Add("LoginName");
                dsUsers.Tables["Info"].Columns.Add("FullName");
                dsUsers.Tables["Info"].Columns.Add("RoleId");
                dsUsers.Tables["Info"].Columns.Add("RoleName");
                dsUsers.Tables["Info"].Columns.Add("OfficeCode");
                dsUsers.Tables["Info"].Columns.Add("BatchId");
                dsUsers.Tables["Info"].Columns.Add("ProcessType");

                for (int iIndex = 0; iIndex < DedicateUsers.Length; iIndex++)
                {
                    dsUsers.Tables["Info"].Rows.Add(new object[]{
                        DedicateUsers[iIndex].EmployeeId,
                        DedicateUsers[iIndex].LoginName,
                        DedicateUsers[iIndex].FullName,
                        DedicateUsers[iIndex].ToRole.RoleId,
                        DedicateUsers[iIndex].ToRole.RoleName,
                        DedicateUsers[iIndex].OfficeCode,
                        DedicateUsers[iIndex].BatchId,
                        DedicateUsers[iIndex].ProcessType
                    });
                }


                Collection<CallWsFunction> CallWsFunctions = new Collection<CallWsFunction> { };
                if (String.IsNullOrEmpty(oLinkCls.RunFunctionId) == false)
                {
                    string[] FunctionIds = oLinkCls.RunFunctionId.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    DataSet ds = new DataSet("XmlFunctionWorkflow");
                    ds.Tables.Add("Wf");
                    ds.Tables["Wf"].Columns.Add("WorkflowDefId");
                    ds.Tables["Wf"].Columns.Add("WorkflowActionId");
                    ds.Tables["Wf"].Columns.Add("RecordId");
                    ds.Tables["Wf"].Columns.Add("WorkflowFunctionId");
                    ds.Tables["Wf"].Columns.Add("RunCommandText");
                    ds.Tables["Wf"].Columns.Add("XmlData");
                    ds.Tables["Wf"].Columns.Add("RunAtServer");
                    ds.Tables["Wf"].Columns.Add("SiteId");

                    for (int iIndex = 0; iIndex < FunctionIds.Length; iIndex++)
                    {
                        string DllPath = oSiteParam.DllPath;
                        FunctionIds[iIndex] = FunctionIds[iIndex].Trim();
                        IWfFunction
                            WfFunction = WorkFlowFunctionMan.Find(DllPath, FunctionIds[iIndex]);
                        if (WfFunction != null)
                        {
                            if (WfFunction.RunAtServer == false)
                            {
                                WfExecuteParamCls oWfExecuteParamCls = new WfExecuteParamCls();
                                oWfExecuteParamCls.RecordId = RecordId;
                                oWfExecuteParamCls.WorkflowDefId = WorkflowDefId;
                                oWfExecuteParamCls.WorkflowActionId = WorkflowActionId;
                                oWfExecuteParamCls.SiteId = SiteId;
                                RetWfExecuteParamCls oRetWfExecuteParamCls = WfFunction.Execute(oWfExecuteParamCls);
                                if (oRetWfExecuteParamCls.Error)
                                {
                                    throw new Exception(oRetWfExecuteParamCls.ReturnMsg);
                                }
                                if (oRetWfExecuteParamCls.ReturnIsLink)
                                {
                                    oDoNextLinkRetCls.Url = oRetWfExecuteParamCls.Url;
                                    //return oDoNextLinkRetCls;
                                }
                                if (oRetWfExecuteParamCls.Done)
                                {
                                    CallWsFunction oCallWsFunction = new CallWsFunction();
                                    oCallWsFunction.Command = WfFunction.WsCommandText;
                                    oCallWsFunction.XmlData = oRetWfExecuteParamCls.XmlData;
                                    oCallWsFunction.RecordId = RecordId;
                                    oCallWsFunction.RunAtServer = WfFunction.RunAtServer;

                                    CallWsFunctions.Add(oCallWsFunction);
                                }
                            }
                            else
                            {
                                ds.Tables["Wf"].Rows.Add(new object[]{
                                    WorkflowDefId,WorkflowActionId,RecordId,FunctionIds[iIndex].Trim(),"","",true,SiteId
                                });
                            }
                        }
                    }
                    WorkflowFunction = ds.GetXml();
                    //doan nay call WebService de xu ly du lieu...!
                }

                string XmlUsers = dsUsers.GetXml();
                string XmlData = "";
                string FlashQueuePath = WebConfig.GetConfigFromXml(oSiteParam, "FlashQueuePath");
                Portal.Workflow.Bussiness.WorkflowBll.DoNextLinkRunAtServerReturnCls
                    oDoNextLinkRunAtServerReturnCls = new WorkflowBll().DoNextLinkRunAtServer(SiteId, null, LinkId, WorkflowActionId, ProcessContent, XmlUsers, XmlData, iProcessDate.ToString(), WorkflowFunction, AttachFileSessionId, AttachedDocumentIds, FlashQueuePath, ResponsibleId, Responsible, JoinerId, Joiner);
                //try
                //{
                //    SystemLogBll.AddBackendSystemLog(SiteId, Environments.CurrentLoginUser.LoginName, oLinkCls.LinkName, WorkflowDefId, wfa.WorkFlowDefCls.WorkFlowName, "NextActivity", "Workflow", "Chuyển trạng thái");
                //}
                //catch { }
                oDoNextLinkRetCls.IsLink = oDoNextLinkRunAtServerReturnCls.IsLink;
                oDoNextLinkRetCls.Url =oSiteParam.HttpRoot+"/admin/home.aspx";// oDoNextLinkRunAtServerReturnCls.Url;
                oDoNextLinkRetCls.ReturnMsg = "Đã chuyển công việc thành công!";
                return oDoNextLinkRetCls;
            }
            catch (Exception ex)
            {
                oDoNextLinkRetCls.IsError = true;
                oDoNextLinkRetCls.ReturnMsg = ex.Message.ToString();
                return oDoNextLinkRetCls;
            }
        }
        #region old

        //[AjaxPro.AjaxMethod]
        //public DoNextLinkRetCls ServerSideDetectUsers(
        //    string SiteId,
        //    string WorkflowDefId, 
        //    string WorkflowActionId,
        //    string RecordId, 
        //    string LinkId)
        //{
        //    DoNextLinkRetCls oDoNextLinkRetCls = new DoNextLinkRetCls();
        //    try
        //    {
        //        WebSessionUtility.CheckSessionTimeOut();
        //        SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
        //        DataTable dtRole = new WorkflowBll().GetWfRoleInLink(oSiteParam.PathRoot, oSiteParam.ConnectionString, WorkflowActionId, LinkId);
        //        string LoginName = WebSessionUtility.GetCurrentLoginUser().LoginName;

        //        string DllPath = oSiteParam.DllPath;// oSiteParam.PathRoot + "\\bin";
        //        string ToUsers = new WorkflowBll().ServerSideGetToUsersByFullName(DllPath, oSiteParam.ConnectionString, WorkflowDefId, WorkflowActionId, LinkId);
        //        string ViewUsers = new WorkflowBll().ServerSideGetViewUsersByFullName(DllPath, oSiteParam.ConnectionString, WorkflowDefId, LinkId);
        //        WorkflowActionInfoCls oWorkflowActionInfoCls = new WorkflowBll().ServerSideCheckStartWorkFlowRecord(oSiteParam.ConnectionString, WorkflowActionId);
        //        if (oWorkflowActionInfoCls.StartWorkflowRecord)
        //        {
        //            if (!String.IsNullOrEmpty(oWorkflowActionInfoCls.SendToUsers))
        //            {
        //                ToUsers = oWorkflowActionInfoCls.SendToUsers;
        //            }
        //        }
        //        Workflow.Library.WorkFlowApp wfa=WorkflowBll.CreateWorkflowAppFromWorkflowAction(oSiteParam.ConnectionString,WorkflowActionId);
        //        LinkCls oLinkCls=wfa.GetLink(LinkId);

        //        string NextLinkInfoText = oLinkCls.NextLinkInfoText;

        //        string Html =
        //           "<div class=\"CssFormSaveUpdate\">\r\n"+
        //           "<table>\r\n" +
        //           "    <tr>\r\n" +
        //           "        <td class=Col1 valign=\"text-top\" style=\"width:140px;\">Nội dung</td>\r\n" +
        //           "        <td class=Col2 valign=\"text-top\"><textarea class=textarea type=textarea style=\"height:50px;\" id=\"txtNote\">"+NextLinkInfoText+"</textarea></td>\r\n" +
        //           //"        <td></td>\r\n" +
        //           "    </tr>\r\n";
        //        if (oLinkCls.ForAllEmployeeInRole == 1 && oLinkCls.FinishThisTask == 0 && oLinkCls.NextForStatus==0)
        //        {
        //            Html +=
        //           "    <tr style=\"display:none\">\r\n" +
        //           "        <td class=Col1 valign=\"text-top\" style=\"width:140px;\">Xử lý</td>\r\n" +
        //           "        <td class=Col2 valign=\"text-top\">\r\n" +
        //           //JQuery.AutoComplete.GetMultiLookUpUser(SiteId,"txtSendToUsers",ToUsers,false)+"\r\n"+
        //           "               <textarea class=textarea type=textarea id=\"txtSendToUsers\">" + ToUsers + "</textarea>\r\n" +
        //           "               <input type=hidden id=\"txtSendToUsersHidden\" value=\"" + ToUsers + "\">\r\n" +
        //           "        </td>\r\n" +
        //          // "        <td style=\"width:40px;\" valign=top><input id=\"cmdSelectWfSendUser\" class=\"button\" type=button value=\"Chọn\" onclick=\"javascript:ClientGetSendUser('txtSendToUsers');\"></td>\r\n" +
        //           "    </tr>\r\n" +
        //           "    <tr style=\"display:none\">\r\n" +
        //           "        <td class=Col1 valign=\"text-top\" style=\"width:140px;valign:top;\">Tham gia</td>\r\n" +
        //           "        <td class=Col2 valign=\"text-top\">\r\n" +
        //           //JQuery.AutoComplete.GetMultiLookUpUser(SiteId, "txtSendToUsersRelation", ViewUsers, true) + "\r\n" +
        //           "               <textarea class=textarea type=textarea id=\"txtSendToUsersRelation\">" + ViewUsers + "</textarea>\r\n" +
        //           "               <input type=hidden id=\"txtSendToUsersRelationHidden\" value=\"" + ViewUsers + "\">\r\n" +
        //           "        </td>\r\n" +
        //           //"        <td valign=top><input id=\"cmdSelectWfViewUser\" class=\"button\" type=button value=\"Chọn\" onclick=\"javascript:ClientGetViewUser('txtSendToUsersRelation');\"></td>\r\n" +
        //           "    </tr>\r\n";
        //        }
        //        if (oLinkCls.FinishThisTask == 0)
        //        {
        //            Html +=
        //               "    <tr style=\"display:none;\">\r\n" +
        //               "        <td class=Col1 valign=\"top\" style=\"width:140px;\">Hạn xử lý</td>\r\n" +
        //               "        <td class=Col2 valign=\"top\">\r\n" +
        //               "               "+LookUpUtilities.GenerateLookUpDate("txtProcessDate")+"\r\n" +
        //               "        </td>\r\n" +
        //               "        <td></td>\r\n" +
        //               "    </tr>\r\n";
        //        }

        //        if (oLinkCls.ShowOwner)
        //        {
        //            Html+=
        //          "    <tr>\r\n" +
        //          "        <td class=Col1 valign=top style=\"width:140px;valign:top;\">Chọn chủ trì</td>\r\n" +
        //          "        <td class=Col2 valign=top>\r\n" +
        //          "               <input id=txtResponsibleId type=hidden>\r\n"+
        //          "               <textarea class=\"CssTextArea\" id=\"txtResponsible\"></textarea>\r\n" +
        //          "        </td>\r\n" +
        //          "        <td valign=top>\r\n"+
        //          "               <input class=\"CssSelectUser\" type=button value=\"Chọn\" onclick=\"javascript:ClientDetectResponsible('txtResponsibleId','txtResponsible');\">\r\n"+
        //          "       </td>\r\n" +
        //          "    </tr>\r\n" +
        //          "    <tr>\r\n" +
        //          "        <td class=Col1 valign=top style=\"width:140px;valign:top;\">Chọn phối hợp</td>\r\n" +
        //          "        <td class=Col2 valign=top>\r\n" +
        //          "               <input id=txtJoinerId type=hidden>\r\n" +
        //          "               <textarea class=\"CssTextArea\" id=\"txtJoiner\"></textarea>\r\n" +
        //          "        </td>\r\n" +
        //          "        <td valign=top><input class=\"CssSelectUser\" type=button value=\"Chọn\" onclick=\"javascript:ClientDetectResponsible('txtJoinerId','txtJoiner');\"></td>\r\n" +
        //          "    </tr>\r\n";
        //        }

        //        Html +=
        //           "    <tr style=\"display:none;\">\r\n" +
        //           "        <td class=Col1 style=\"width:140px;\">Tài liệu gắn kèm</td>\r\n" +
        //           "        <td class=Col2>\r\n" +
        //           "            <div  id=\"divFileAttachInfo\">" + DrawAttachInfo(SiteId, SessionId) + "</div><input type=\"button\" class=cssAttachFile onclick=\"javascript:ClientUploadFile('divFileAttachInfo','" + SessionId + "');\" value=\"Chọn file gửi kèm\">\r\n" +
        //           "        </td>\r\n" +
        //           "        <td></td>\r\n" +
        //           "    </tr>\r\n" +
        //           "</table>\r\n" +
        //           "</div>\r\n";
                
        //        oDoNextLinkRetCls.ReturnMsg = Html;
        //        return oDoNextLinkRetCls;
        //    }
        //    catch (Exception ex)
        //    {
        //        oDoNextLinkRetCls.IsError = true;
        //        oDoNextLinkRetCls.ReturnMsg = ex.Message.ToString();
        //        return oDoNextLinkRetCls;
        //    }
        //}


        
        //[AjaxPro.AjaxMethod]
        //public string DrawAttachInfo(string SiteId, string SessionId)
        //{
        //    string Html = "";
        //    SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);

        //    string PathSave = oSiteParam.PathRoot + "\\media\\" + oSiteParam.SiteId + "\\TempUploadFiles\\" + SessionId;
        //    System.IO.Directory.CreateDirectory(PathSave);
        //    if (new System.IO.DirectoryInfo(PathSave).Exists)
        //    {
        //        Html = "<table>";
        //        string[] Files = System.IO.Directory.GetFiles(PathSave);

        //        for (int iIndex = 0; iIndex < Files.Length; iIndex++)
        //        {
        //            System.IO.FileInfo fi = new System.IO.FileInfo(Files[iIndex]);
        //            Html += " <tr>" +
        //                      "     <td>" + fi.Name + "</td>" +
        //                      "     <td><a href=\"javascript:ClientRemoveFile('" + SessionId + "','" + fi.Name + "');\">hủy bỏ</a></td>" +
        //                      " </tr>";
        //        }
        //        Html += "</table>";
        //    }
        //    else
        //    {
        //        Html = "";
        //    }
        //    return Html;
        //}


        //[AjaxPro.AjaxMethod]
        //public string ServerSideGetOriginUrl(string SiteId, string WorkflowActionId)
        //{
        //    try
        //    {
        //        SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
        //        WorkFlowRecordCls oWorkFlowRecordCls=WorkflowBll.CreateWorkFlowRecord(oSiteParam.ConnectionString, WorkflowActionId);

        //        ParamPreviewFromWorkflowCls oParamPreviewFromWorkflowCls = new ParamPreviewFromWorkflowCls();
        //        oParamPreviewFromWorkflowCls.SiteId = SiteId;
        //        oParamPreviewFromWorkflowCls.RecordId = oWorkFlowRecordCls.RecordId;
        //        oParamPreviewFromWorkflowCls.WorkflowActionId = WorkflowActionId;
        //        oParamPreviewFromWorkflowCls.WorkflowDefId = oWorkFlowRecordCls.WorkFlowDefId;

        //        string PreviewUrl = oWorkFlowRecordCls.PreviewUrl;
        //        string TempUrl = PlugInViewFromWorkflowUtilities.GetPreviewUrl(oSiteParam.DllPath, oWorkFlowRecordCls.ExtraInfo, oParamPreviewFromWorkflowCls);
        //        if (string.IsNullOrEmpty(TempUrl) == false)
        //        {
        //            PreviewUrl = TempUrl;
        //        }
        //        return PreviewUrl;
        //    }
        //    catch (Exception ex)
        //    {
        //        return "ERROR: " + ex.Message.ToString();
        //    }
        //}


        //class TempUserCls
        //{
        //    public string LoginName;
        //    public bool IsTo = true;
        //}

#endregion

        public static string GetLinkButton(string SiteId,
            string WorkflowDefId,
            string WorkflowActionId,
            string RecordId)
        {
            SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string Html = "";
            string LoginName = WebSessionUtility.GetCurrentLoginUser().LoginName;
            string CurrentLoginOffice = WebSessionUtility.GetCurrentLoginUser().AssetCode;

            DataTable dtNextLinks = new WorkflowBll().GetNextLinks(oSiteParam.DllPath, oSiteParam.ConnectionString, WorkflowActionId, LoginName, CurrentLoginOffice);
            DataView dvLinks = new DataView(dtNextLinks, "", "SortIndex ASC", DataViewRowState.CurrentRows);
            string ButtonUrl = WebConfig.GetButtonIconRoot(oSiteParam) + "\\LinkWorkflow.png";
            for (int iIndex = 0; iIndex < dvLinks.Count; iIndex++)
            {
                string LinkId = (string)dvLinks[iIndex]["LinkId"];
                string ButtonLink = (string)dvLinks[iIndex]["ButtonLink"];
                string LinkButtonStatusId = "";
                try
                {
                    if (dvLinks[iIndex]["LinkButtonStatusId"] != DBNull.Value)
                    {
                        LinkButtonStatusId = (string)dvLinks[iIndex]["LinkButtonStatusId"];
                    }
                }
                catch { }
                bool AllowVisible = true;
                if (!string.IsNullOrEmpty(LinkButtonStatusId))
                {
                    IWorkflowButtonLinkStatus 
                        OWorkflowButtonLinkStatus = WorkflowButtonLinkStatusUtility.Find(oSiteParam.DllPath, LinkButtonStatusId);
                    if (OWorkflowButtonLinkStatus != null)
                    {
                        CheckWorkflowButtonLinkStatus OCheckWorkflowButtonLinkStatus = new CheckWorkflowButtonLinkStatus();
                        OCheckWorkflowButtonLinkStatus.ObjectId = RecordId;
                        OCheckWorkflowButtonLinkStatus.WorkflowActionId = WorkflowActionId;
                        OCheckWorkflowButtonLinkStatus.WorkflowDefId = WorkflowDefId;
                        AllowVisible = OWorkflowButtonLinkStatus.CheckStatus(SiteId, OCheckWorkflowButtonLinkStatus).RetBoolean;
                    }
                }
                if (AllowVisible)
                {
                    ///Edit by dvtien 02/11/2014
                    //Todo: fix url to rewrite for sbv
                    
                    Html += "<li><div><img  src=\"" + ButtonUrl + "\" style=\"height:16px;\"><div><div><a href=\"javascript:ProcessWorkflow('" + WorkflowDefId + "','" + WorkflowActionId + "','" + RecordId + "','" + LinkId + "');\">" + ButtonLink + "</a></div></li>\r\n";
                }
            }
            return Html;
        }
            

        public static string GetNextLinkForm(
            string SiteId,
            string WorkflowDefId,
            string WorkflowActionId,
            string RecordId,
            string SelectedLinkId)
        {

            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string Html = "";
               
                WorkFlowApp wfa=WorkflowBll.CreateWorkflowAppFromWorkflowAction(oSiteParam.ConnectionString,WorkflowActionId);
                LinkCls OLink = new WorkflowBll().GetLink(wfa,SelectedLinkId);
                string ButtonRoot = WebConfig.GetButtonIconRoot(oSiteParam);
                AjaxOut AjaxOutGetRoleForLink = ServerSideGetRoleForNextLink(SiteId, wfa, WorkflowDefId, WorkflowActionId, RecordId, OLink);
                string WfCheckRoleIds = AjaxOutGetRoleForLink.RetExtraParam1;
                string CssCol2 = "display:block";
                if (AjaxOutGetRoleForLink.RetNumber <= 1)
                {
                    CssCol2 = "display:none";
                }
                Html =
                " <div class=DatabaseFunction>\r\n" +
                " <ul>\r\n" +
                "       <li onclick=\"javascript:ClientDoNextLink('" + SelectedLinkId + "');\"><img class=image src=\"" + ButtonRoot + "/Workflow.png\"><div>Thực hiện chuyển</div></li>\r\n" +
                "       <li onclick=\"javascript:ClientCancelDoNextLink();\"><img class=image src=\"" + ButtonRoot + "/Back.png\"><div>Hủy quay lại</div></li>\r\n" +
                " </ul>\r\n" +
                " </li>\r\n" +
                 "<input type=\"hidden\" id=\"txtWorkflowActionId\" value=\"" + WorkflowActionId + "\">\r\n" +
                 "<input type=\"hidden\" id=\"txtWorkflowDefId\" value=\"" + WorkflowDefId + "\">\r\n" +
                 "<input type=\"hidden\" id=\"txtRecordId\" value=\"" + RecordId + "\">\r\n" +
                 "<input type=\"hidden\" id=\"txtWfCheckRoleIds\" value=\""+WfCheckRoleIds+"\">\r\n"+
                 //"<input type=\"hidden\" id=\"txtExtraInfo\" value=\"\">\r\n" +
                 "<div class=CssNextWorkflowForm>\r\n" +
                 "<table>\r\n"+
                 "  <tr>\r\n"+
                 "      <td class=Col1>\r\n"+
                 "          <div class=RowItem>Nhập ý kiến xử lý</div>\r\n" +
                 "          <div class=RowItem><textarea type=textarea class=textarea id=txtProcessContent>" + OLink.NextLinkInfoText + "</textarea></div>\r\n" +
                 "      </td>\r\n"+
                 "      <td class=Col2 style=\""+CssCol2+"\">\r\n" +
                            AjaxOutGetRoleForLink.HtmlContent+
                 "      </td>\r\n" +
                 
                 "  </tr>\r\n"+
                 "</div>\r\n";
                
                return Html;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        public static AjaxOut ServerSideGetRoleForNextLink(
            string SiteId,
            WorkFlowApp wfa,
            string  WorkflowDefId,
            string  WorkflowActionId,
            string  RecordId,
            LinkCls OLink)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            Collection<Systems.Model.RoleCls>
                ColRoles = new Collection<Systems.Model.RoleCls> { };

            try
            {
                WorkFlowRecordCls OWorkflowRecord = WorkflowBll.CreateWorkFlowRecord(OSiteParam.ConnectionString, WorkflowActionId);
                if (OWorkflowRecord == null)
                {
                    throw new Exception("Dữ liệu không tồn tại hoặc quy trình đã bị xóa!");
                }
                else
                {
                    string Html =
                        "<div class=\"RowItem\">Chuyển đến vị trí</div>\r\n";
                    if (OLink.RoleIds.Length == 0)
                    {
                        if (OLink.FinishThisTask == 0)
                        {
                            if (OLink.ForAllEmployeeInRole == 0)
                            {
                                Html += "<div class=CssNoData>Đường chuyển trả lại cho người gửi</div>\r\n";
                            }
                            else
                            {
                                Html += "<div class=CssNoData>Không có đối tượng chuyển</div>\r\n";
                            }
                        }
                        else
                        {
                            Html += "<div class=CssNoData>Đường chuyển kết thúc quy trình</div>\r\n";
                        }
                    }
                    else
                    {
                        //Đây là group roles...! Vì map vào group role....!
                        string[] WorkflowGroupRoleIds = OLink.RoleIds;//đây là role của workflow...!


                        bool ActionRoleRelation = false;
                        DataSet dsRoleRelation = new DataSet();
                        if (!string.IsNullOrEmpty(OLink.RoleRelationTemplateId))
                        {
                            Systems.Model.RoleRelationTemplateCls
                                ORoleRelationTemplate = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleRelationTemplateModel(SiteId, OLink.RoleRelationTemplateId);
                            if (!string.IsNullOrEmpty(ORoleRelationTemplate.XmlData))
                            {
                                ActionRoleRelation = true;
                                dsRoleRelation = new DataSet();
                                dsRoleRelation.ReadXml(new StringReader(ORoleRelationTemplate.XmlData));
                            }
                        }

                        string[] GroupRoleIds = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ConvertSystemGroupRoleFromWorkflowGroupRole(SiteId, WorkflowDefId, WorkflowGroupRoleIds);
                        //đổi sang role của hệ thống
                        Hashtable hs = new Hashtable();
                        for (int iIndexGroupRole = 0; iIndexGroupRole < GroupRoleIds.Length; iIndexGroupRole++)
                        {
                            //lay danh sách role ra
                            Systems.Model.RoleCls[] Roles = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingRoleForGroupRole(SiteId, GroupRoleIds[iIndexGroupRole]);
                            for (int iIndexRole = 0; iIndexRole < Roles.Length; iIndexRole++)
                            {
                                if (hs.ContainsKey(Roles[iIndexRole].RoleId) == false)
                                {
                                    //doan nay check xem relation the nao
                                    bool AllowAdded = true;
                                    if (ActionRoleRelation)
                                    {
                                        AllowAdded = false;
                                        for (int iRoleRelation = 0; iRoleRelation < dsRoleRelation.Tables[0].Rows.Count; iRoleRelation++)
                                        {
                                            string FromRoleId = dsRoleRelation.Tables[0].Rows[iRoleRelation]["FromRoleId"].ToString();
                                            string ToRoleId = dsRoleRelation.Tables[0].Rows[iRoleRelation]["ToRoleId"].ToString();
                                            if (FromRoleId.Equals(WebSessionUtility.GetCurrentLoginUser().RoleId) && ToRoleId.Equals(Roles[iIndexRole].RoleId))
                                            {
                                                AllowAdded = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (AllowAdded)
                                    {
                                        ColRoles.Add(Roles[iIndexRole]);
                                        hs.Add(Roles[iIndexRole].RoleId, Roles[iIndexRole]);
                                    }
                                }
                            }
                        }


                        //remove nhung thang khong co ra
                        if (!string.IsNullOrEmpty(OLink.DetectRoleServiceId))
                        {
                            IDetectRoleForNext FoundDetectRoleForNext = DetectRoleForNextUtility.Find(OSiteParam.DllPath, OLink.DetectRoleServiceId);
                            if (FoundDetectRoleForNext != null)
                            {
                                string CreatedByRoleId = "";
                                string[] RoleIds = FoundDetectRoleForNext.GetRoleIds(SiteId, WorkflowDefId, WorkflowActionId, RecordId, CreatedByRoleId);
                                for (int iIndex = 0; iIndex < RoleIds.Length; iIndex++)
                                {
                                    int iCheck = 0;
                                    while (iCheck < ColRoles.Count)
                                    {
                                        if (RoleIds[iIndex].Equals(ColRoles[iCheck].RoleId))
                                        {
                                            ColRoles.RemoveAt(iCheck);
                                        }
                                        else
                                        {
                                            iCheck++;
                                        }
                                    }
                                }
                            }
                        }

                        Html +=
                            "<div class=\"ulWorkflowRole\">\r\n" +
                            "<table>\r\n";
                        OAjaxOut.RetExtraParam1 = "";
                        for (int iIndex = 0; iIndex < ColRoles.Count; iIndex++)
                        {
                            OAjaxOut.RetExtraParam1 = OAjaxOut.RetExtraParam1 + "$" + ColRoles[iIndex].RoleId + "$";
                            if (iIndex < ColRoles.Count - 1)
                            {
                                OAjaxOut.RetExtraParam1 += ";";
                            }
                            Html += " <tr>\r\n" +
                                    "   <td style=\"width:10px;\"><input id=\"chkWfRole" + ColRoles[iIndex].RoleId + "\" type=checkbox class=CssCheckBoxWfRole CHECKED onchange=\"javascript:ClientWorkflowProcessRoleCheckChange('" + ColRoles[iIndex].RoleId + "');\"></td>\r\n" +
                                    "   <td>" + ColRoles[iIndex].RoleName + "</td>\r\n" +
                                    " </tr>\r\n";
                        }
                        Html += "</table>\r\n" +
                            "</div>\r\n";
                    }
                    OAjaxOut.HtmlContent = Html;
                    OAjaxOut.RetNumber = ColRoles.Count;
                    int DebugMode = 0;
                    try
                    {
                        DebugMode = int.Parse(WebConfig.GetConfigFromXml(OSiteParam, "DebugMode"));
                    }
                    catch { }
                    if (DebugMode == 1)
                    {
                        OAjaxOut.RetNumber = 2;
                    }
                }
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.RetNumber = 2;//dat co = 2 de bao loi le
            }
            return OAjaxOut;
        }

    }
}
